package com.tpv.app.volley.demo.util;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;

import java.io.UnsupportedEncodingException;

public class JsonObjectRequest<T> extends Request<T>
{
    /**
     * Default charset for JSON request.
     */
    protected static final String PROTOCOL_CHARSET = "utf-8";
    
    /**
     * Content type for request.
     */
    private static final String PROTOCOL_CONTENT_TYPE = String.format("application/json; charset=%s", PROTOCOL_CHARSET);
    
    /**
     * Lock to guard mListener as it is cleared on cancel() and read on delivery.
     */
    private final Object mLock = new Object();
    
    
    private GsonVolleyListener<T> mListener;
    
    private final String mRequestBody;
    
    
    public JsonObjectRequest(int method, String url,String requestBody,GsonVolleyListener listener)
    {
        super(method, url, listener);
        mListener = listener;
        mRequestBody = requestBody;
    }
    
    @Override
    public void cancel()
    {
        super.cancel();
        synchronized (mLock)
        {
            mListener = null;
        }
    }
    
    @Override
    protected void deliverResponse(T response)
    {
        Response.Listener<T> listener;
        synchronized (mLock)
        {
            listener = mListener;
        }
        if (listener != null)
        {
            listener.onResponse(response);
        }
    }
 
    
    /**
     * @deprecated Use {@link #getBodyContentType()}.
     */
    @Deprecated
    @Override
    public String getPostBodyContentType()
    {
        return getBodyContentType();
    }
    
    /**
     * @deprecated Use {@link #getBody()}.
     */
    @Deprecated
    @Override
    public byte[] getPostBody()
    {
        return getBody();
    }
    
    @Override
    public String getBodyContentType()
    {
        return PROTOCOL_CONTENT_TYPE;
    }
    
    @Override
    public byte[] getBody()
    {
        try
        {
            return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
        } catch (UnsupportedEncodingException uee)
        {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, PROTOCOL_CHARSET);
            return null;
        }
    }
    
    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response)
    {
        try
        {
            String parse =new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            Response.success(parse,HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        return null;
    }
}
